package ink.sunflowerk.interceptor;

import ink.sunflowerk.exception.AccessForbiddenException;
import ink.sunflowerk.pojo.Teacher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器
 * 如果没有 teacher 就让他登录
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 通过 request对象获取 session对象
        HttpSession session = request.getSession();
        //2. 尝试从 session域中获取 Admin对象
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        //3. 判断 admin对象否为空
        System.out.println("preHandle====>>" + teacher);
        if (teacher == null) {
            //4. 抛出异常
//            throw new AccessForbiddenException("请登录以后在访问！");
            response.sendRedirect("/login.jsp");
        }
        //5. 如果 admin对象不为 null，则返回 true放行
        return true;
    }
}